package com.example.androidproject.novel.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.androidproject.R;
import com.example.androidproject.app.adapter.RecycelViewAdapter;
import com.example.androidproject.myview.MyListView;
import com.example.androidproject.base.BaseFragment;
import com.example.androidproject.novel.activity.CatalogueActivity;
import com.example.androidproject.novel.adapter.RecommendAdapter;
import com.example.androidproject.novel.bean.NovelBean;
import com.example.androidproject.utils.GlobalFunction;
import com.example.androidproject.utils.RequestConstant;
import com.example.androidproject.utils.RequestParameters;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NovelFragment extends BaseFragment {
    private static final String TAG = "GGSTUDY";
    private TextView nav_tv, login_tv;
    private OkHttpClient okHttpClient;
    private RecyclerView rv_novel;
    private MyListView lv_novel_recomment;

    private List<NovelBean.DataBean> RecommentList = new ArrayList<>();
    int total = 0;

    CountDownLatch latch = new CountDownLatch(3);

    @Override
    public View initView() {
//        GlobalFunction.dialogVisibilityHandler.sendMessage(new Message());
        Log.e(TAG, "小说视图被初始化了");
        View view = View.inflate(mContext, R.layout.fragment_novel, null);
//        nav_tv = view.findViewById(R.id.nav_tv);
//        login_tv = view.findViewById(R.id.login_tv);
        rv_novel = view.findViewById(R.id.rv_novel);
        lv_novel_recomment = view.findViewById(R.id.lv_novel_recomment);
        okHttpClient = new OkHttpClient();
        initListener();
        return view;
    }


    private void initListener() {
    }

    @Override
    public void initData() {
        super.initData();
        Log.e(TAG, "小说数据被初始化了");
        getBannerDataFromNet();
        getClassicNewContent();
        getClassicHotContent();
        getHotRecommentContent();
    }

    /**
     * 获取Banner横幅条的数据
     */
    private void getBannerDataFromNet() {
        String classify = RequestParameters.CLASSIFY;
        int limit = 3;
        int page = RequestParameters.PAGE;
        String url = RequestConstant.NOVEL_URL + "?" + "classify=" + classify + "&limit=" + limit + "&page=" + page;
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 失败
                Log.d(TAG, "onFailure: " + e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                // 成功
                if (response.isSuccessful()) {
                    processData(response.body().string(), 1);
                } else {
                    Log.d(TAG, "onResponse: 请求失败->" + response.code());
                }
            }
        });
    }

    /**
     * body
     */

    private void getClassicNewContent() {
        String classify = "全部";
        int limit = 3;
        int page = 1;
        String url = RequestConstant.NOVEL_URL + "?classify=" + classify + "&limit=" + limit + "&page=" + page;
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    processData(response.body().string(), 2);
                    latch.countDown();
                } else {
                    Looper.prepare();
                    Log.d(TAG, "onResponse: 请求失败->" + response.code());
                    Toast.makeText(mContext, "请求失败", Toast.LENGTH_SHORT).show();
//                    GlobalFunction.dialogGONEHandler.sendMessage(new Message());
                    Looper.loop();
                }
            }
        });
    }

    private void getClassicHotContent() {
        String classify = "全部";
        int limit = 3;
        int page = 2;
        String url = RequestConstant.NOVEL_URL + "?classify=" + classify + "&limit=" + limit + "&page=" + page;
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    processData(response.body().string(), 3);
                    latch.countDown();
                } else {
                    Looper.prepare();
                    Log.d(TAG, "onResponse: 请求失败->" + response.code());
                    Toast.makeText(mContext, "请求失败", Toast.LENGTH_SHORT).show();
//                    GlobalFunction.dialogGONEHandler.sendMessage(new Message());
                    Looper.loop();
                }
            }
        });
    }

    private void getHotRecommentContent() {
        String classify = "全部";
        int limit = 3;
        int page = 3;
        String url = RequestConstant.NOVEL_URL + "?classify=" + classify + "&limit=" + limit + "&page=" + page;
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    processData(response.body().string(), 4);
                    latch.countDown();
                } else {
                    Looper.prepare();
                    Log.d(TAG, "onResponse: 请求失败->" + response.code());
                    Toast.makeText(mContext, "请求失败", Toast.LENGTH_SHORT).show();
//                    GlobalFunction.dialogGONEHandler.sendMessage(new Message());
                    Looper.loop();
                }
            }
        });
    }

    private void processData(String json, int flag) {
        Gson gson = new Gson();
        NovelBean novelBean = gson.fromJson(json, NovelBean.class);
        ArrayList<NovelBean.DataBean> data = (ArrayList<NovelBean.DataBean>) novelBean.getData();

        if (novelBean.getStatus() == 0) {
            if (data != null) {
                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putInt("total", novelBean.getTotal());
                msg.setData(bundle);
                if (flag == 1) {
                    // Banner
                    bundle.putParcelableArrayList("data", data);
                    bannerhandler.sendMessage(msg);
                } else if (flag == 2) {
                    // ClassicNewBody
                    RecommentList.addAll(data);
                } else if (flag == 3) {
                    // ClassicHotBody
                    RecommentList.addAll(data);
                } else if (flag == 4) {
                    // HotRecommentBody
                    RecommentList.addAll(data);

                    bodyhandler.sendMessage(msg);
                }
            } else {
                // 没有数据
                Toast.makeText(mContext, "没有数据", Toast.LENGTH_SHORT).show();
            }
        } else {
            Log.d(TAG, "processData: 请求失败->" + novelBean.getStatus());
        }
    }


    //
    @SuppressLint("HandlerLeak")
    public Handler bannerhandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            ArrayList<NovelBean.DataBean> data = msg.getData().getParcelableArrayList("data");
            rv_novel.setLayoutManager(new GridLayoutManager(mContext, 1));
            RecycelViewAdapter adapter = new RecycelViewAdapter(mContext, data, 2);
            rv_novel.setAdapter(adapter);
        }
    };
    //
    @SuppressLint("HandlerLeak")
    public Handler bodyhandler = new Handler(Looper.getMainLooper()) {
        private RecommendAdapter adapter;

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ArrayList<NovelBean.DataBean> ClassicNewBody = new ArrayList<>();
            ArrayList<NovelBean.DataBean> ClassicHotBody = new ArrayList<>();
            ArrayList<NovelBean.DataBean> HotRecommentBody = new ArrayList<>();
            for (int i = 0; i < RecommentList.size(); i++) {
                if (i < 3) {
                    ClassicNewBody.add(RecommentList.get(i));
                } else if (i < 6) {
                    ClassicHotBody.add(RecommentList.get(i));
                } else {
                    HotRecommentBody.add(RecommentList.get(i));
                }
            }
            adapter = new RecommendAdapter(mContext, ClassicNewBody, ClassicHotBody, HotRecommentBody);
            lv_novel_recomment.setAdapter(adapter);
            adapter.setOnItemClickListener(new RecommendAdapter.setOnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(mContext, CatalogueActivity.class);
                    Bundle bundle = new Bundle();
                    //因为三个组件的内容是RecommentList拆开来的 所以没办法将每一个组件的内容都精准发给catalogueActivity
                    bundle.putParcelable("data", RecommentList.get(position));
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                }
            });
            // classify 先从这里改，把scrollview 改成gridview这些来 因为scrollview真的会卡
        }
    };

    //返回键进入后台后 重新进入会加载不到数据 必须得在后台也把应用给关了，重新开才行这是个问题
    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: 123");
    }
}
